<?
/*
   Simple template class which can load template from file or url and replace 
   [content]
*/
class Template 
{
	function Template ()
    {
      //constructor
	}

    //return block which placed between $start_tag and $end_tag
    function getBlock($template,$start_tag,$end_tag)   
    {
      $pos = strpos($template,$start_tag);
      if ($pos === false) 
      { 
   	    return "";
      }else
      {
        $block = substr($template,$pos+strlen($start_tag));             
        if(strlen(trim($block))>0)
        {  
          $pos = strpos($block,$end_tag);
          if ($pos === false) 
          { 
         	   return "";
          }else
          {
            return substr($block,0,$pos);  
          }  
        }else
        {
          return "";
        }
      }
    }

    //cut block which placed between $start_tag and $end_tag and return new template
    function cutBlock($template,$start_tag,$end_tag,$replace_tag="")   
    {
      $header = "";
      $footer = "";
      
      $pos = strpos($template,$start_tag);
      if ($pos === false) 
      { 
   	    return $template;
      }else
      {
          $header = substr($template,0,$pos);             
  
          $pos = strpos($template,$end_tag);
          if ($pos === false) 
          { 
           	   return $header;
          }else
          {
            $footer = substr($template,$pos+strlen($end_tag));             
          }  
      }            
      return $header.($replace_tag!=""?$replace_tag:"").$footer;
    }

    function loadTemplateFromString($template,$replaces) 
    {
        foreach ($replaces as $sName=>$sValue)
        {
//   	    echo "<br>replace: ".$sName." with: ".$sValue;
          $template = str_replace($sName,$sValue,$template); 
    	}
        return $template;
	}
		
	function loadTemplateFromFile($filename,$replaces) 
    {
      echo $this->loadTemplateFromString(file_get_contents($filename),$replaces);       
	}
		
	function loadTemplateFromURL($url,$replaces,$tmpstorage)
    {
      $http     = new Http();
      $filename = $tmpstorage."tmpl_".uniqid('').".html";
      
      $error = $http->GET($url,"",$filename); 
          
      if(strlen($error)==0)
      {    
         $this->loadTemplateFromFile($filename,$replaces); 
      }else
      {
        echo "ERROR: ".$error;
      }     
      //@unlink($filename);    
    }
}
?>
